package cn.alise.controller.login;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.alise.consts.BaseConsts;
import cn.alise.consts.ConfigConsts;
import cn.alise.controller.common.BaseController;
import cn.alise.enums.EnumClass;
import cn.alise.qdp.model.menu.Menu;
import cn.alise.qdp.model.user.User;
import cn.alise.qdp.service.admin.MenuService;
import cn.alise.qdp.service.log.UserAccessLogsService;
import cn.alise.qdp.service.user.UserService;
import cn.alise.util.JSONResult;
import cn.alise.util.Md5;

import com.alibaba.fastjson.JSONArray;

/**
* ClassName: LoginController <br/>
* Description: 登录控制类. <br/>
*/
@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {
	private static final long serialVersionUID = 639158305794032015L;
	
	private static final String ERROR_TITLE_KEY = "error_title";
	private static final String REDIRECT_LOGIN  = "redirect:/login/forward";
	
	@Resource(name = "userService")
	private UserService userService;
	
	@Resource(name = "menuService")
	private MenuService menuService;
	
	@Resource(name = "userAccessLogsService")
	private UserAccessLogsService userAccessLogsService;
	
	/**
	 * 企业会员登录方法 <br/>
	 * 适用条件：企业用户输入账号和密码登录，这里的登录做登录用户名和密码的校验<br/>
	 * 不保存SESSION的会话信息，具体的会话保存需要在前端的WEB项目中进行处理
	 *
	 */
	@RequestMapping(value = "/forward", method=RequestMethod.GET)
	public String forward(HttpServletRequest request, Model model) {
		return "pages/login/login";
	}
	
	/**
	 * 清除菜单cookie
	 */
	private void clearMenuCookie(HttpServletResponse response ) {
		// 清除菜单
		try {
			Cookie cookie = new Cookie("facs_merchant_menu", null);
			cookie.setMaxAge(0);
			cookie.setPath("/");
			response.addCookie(cookie);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 企业会员登录方法 <br/>
	 */
	/**
	 * @param request
	 * @param response
	 * @param account
	 * @param attr
	 * @return
	 */
	@RequestMapping(value = "/sign")
	public String sign(HttpServletRequest request, HttpServletResponse response, User account, RedirectAttributes attr) {
		this.clearMenuCookie(response);
		Map<String,String> accessLogsMap=new HashMap<String,String>();
		accessLogsMap.put("ipaddress", this.getIpAddr());//获取登录的ip地址
		
		//保存登录时的用户名
		attr.addFlashAttribute("userName",account.getAccount());
		
		// 首先判断用户是否已经处于登录状态,处于登录状态时直接进入后台管理页面;
		User sessionacct = this.getAccountFromSession();
		if (sessionacct != null) {
			return "pages/common/index";
		}
		
		// 对用户输入的账号进行空值判断
		if (!StringUtils.hasText(account.getAccount())) {
			attr.addFlashAttribute(ERROR_TITLE_KEY, "请输入账号！");
			return REDIRECT_LOGIN;
		}
		
		// 对用户输入的密码进行空值判断
		if (!StringUtils.hasText(account.getPassword())) {
			attr.addFlashAttribute(ERROR_TITLE_KEY, "请输入密码！");
			return REDIRECT_LOGIN;
		}
		
		 //调用调用登录校验接口，此接口只是对用户的登录名，密码合法性进行校验
		 Map<String,Object> checkFlag = this.loginCheck(request, response, account);
		 if (!"0".equals(checkFlag.get("code"))) {
			 attr.addFlashAttribute(ERROR_TITLE_KEY, checkFlag.get("msg"));
			 return REDIRECT_LOGIN;
		 }
		 User userInfo = (User)checkFlag.get("user");
		 
		 // 保存信息到Session中
		 this.setSessionValue(BaseConsts.IUser.USER_SESSION_KEY, userInfo);
		 this.setSessionValue(BaseConsts.IUser.USER_NAME, userInfo.getUserName());//用户名
		 this.setSessionValue(BaseConsts.IUser.USER_PATH, userInfo.getPath());//用户头像
		 this.setSessionValue(BaseConsts.IUser.ORGAN_NAME, userInfo.getOrganName());//机构名称
		 this.setSessionValue(BaseConsts.IUser.USER_TYPE, userInfo.getType());//用户类型
		 this.setSessionValue(BaseConsts.IUser.ACCOUNT, userInfo.getAccount());//用户类型
		 
		 // 获取菜单
		 // 获取一级菜单
		 List<Menu> menuNew = new ArrayList<Menu>();
		 Menu menu = new Menu();
		 menu.setMenuId(userInfo.getUserId());//备注：在此以menuId代替userId传值
		 List<Menu> menu1 = this.menuService.getOneListInit(menu);
		 for(int i=0; i<menu1.size(); i++) {
		 	 Menu treeOne = new Menu();
		 	 treeOne.setMenuId(menu1.get(i).getMenuId());
		  	 treeOne.setMenuName(menu1.get(i).getMenuName());
		  	 treeOne.setIconPath(menu1.get(i).getIconPath());
		  	 treeOne.setDataHref(menu1.get(i).getDataHref());
			
			 //获取二级菜单
			 menu.setParentId(menu1.get(i).getMenuId());
			 List<Menu> menu2 = this.menuService.getTwoListInit(menu);
			 if (menu2.size() > 0 ) {
				 menuNew.add(treeOne);
				 for(int j=0; j<menu2.size(); j++) {
					 Menu treeTwo = new Menu();
					 treeTwo.setMenuName(menu2.get(j).getMenuName());
					 treeTwo.setDataId(menu2.get(j).getDataId());
					 treeTwo.setDataHref(menu2.get(j).getDataHref());
					 treeTwo.setIconPath(menu2.get(j).getIconPath());
					 if(j+1 >= menu2.size()) {
						 treeTwo.setEndFlag("yes");
					 }
					 
					 menuNew.add(treeTwo);
				 }
			 } else {
				 treeOne.setEndFlag("yes");
				 menuNew.add(treeOne);
			 }
		 }
		 this.setSessionValue(BaseConsts.IUser.MENU, menuNew);
		 
		 // 从定向到主页
		 return "pages/common/index";
	}
	
	/**
	 * 登出功能
	 */
	@RequestMapping(value = "/logout", method=RequestMethod.GET)
	public String logout(HttpServletRequest request, HttpServletResponse response, User account) {
		
		this.removeSessionValue(BaseConsts.IUser.USER_SESSION_KEY);
//		this.clearCookie(request, response);
		this.getSession().invalidate();
		
		return REDIRECT_LOGIN;
	}
	
	/**
	 * 进入修改密码页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/editPassword", method=RequestMethod.GET)
	public String editPassword(HttpServletRequest request, Model model) {
		model.addAttribute("regexFlag",ConfigConsts.REGEX_FLAG);
		return "pages/login/login-pwd";
	}
	
	/**
	 * 修改密码
	 */
	@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
	public void updatePassword(HttpServletRequest request, HttpServletResponse response){

		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		JSONResult result = new JSONResult();
		
		// session中获取用户信息
		Long userId = this.getAccountFromSession().getUserId();
		
		//根据登录账号获取用户信息
		User user = new User();
		user.setUserId(userId);
		user = this.userService.get(user);
		
		// 验证原密码的有效性 
		String oldpwd = Md5.md5(oldPassword + user.getMask().toString());
		
		if (oldpwd.equals(user.getPassword())) {//验证有效
			// 开始保存新密码
			String newpwd = Md5.md5(newPassword + user.getMask().toString());
			user.setPassword(newpwd);
			int row = this.userService.update(user);
			if(row > 0) {
				result.setMessage("密码修改成功！");
			} else {
				result.setStatus(-1);
				result.setMessage("密码修改失败！");
			}
			getPrintWriter(response,JSONArray.toJSONString(result));
		} else {
			result.setStatus(-1);
			result.setMessage("原密码不正确,修改失败！");
			getPrintWriter(response,JSONArray.toJSONString(result));
		}
	}
	
	/**
	 * 清除cookie
	 */
	public void clearCookie(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		try {
			if (cookies != null) {
				for (Cookie cookie2 : cookies) {
					Cookie cookie = new Cookie(cookie2.getName(), null);
					cookie.setMaxAge(0);
					cookie.setPath("/");
					response.addCookie(cookie);
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}  
	
	/**
	 * 404跳转
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/error404")
	public String error404(HttpServletRequest request, Model model) {
		return "error/404";
	}
	
	/**
	 * 登陆账号密码等检测
	 */
	private Map<String,Object> loginCheck(HttpServletRequest request, HttpServletResponse response, User user) {
		
		Map<String,Object> map = new HashMap<String,Object>();
		
		User userAccount = new User();
		userAccount.setAccount((user.getAccount()).replace(" ", ""));
		
		//根据登录账号获取用户信息
		User entity = this.userService.getLoginInfo(userAccount);
		
		//验证用户账号的有效性
		if(entity==null) {
			map.put("code", "1");
			map.put("msg", "用户账号或密码错误！");
			return map;
		}
		
		//验证用户密码的有效性 
		String pwd = Md5.md5(user.getPassword() + entity.getMask().toString());
		if (!pwd.equals(entity.getPassword())) {
			map.put("code", "2");
			map.put("msg", "用户账号或密码错误！");
			return map;
		}
		
		//验证用户账号状态是否正确
		if(entity.getStatus() != EnumClass.UserStatus.VALID.getKey()) {
			map.put("code", "3");
			map.put("msg", "当前用户帐号已被注销！");
			return map;
		}
			
		//修改账户登录信息
		User newaccount = new User();
		newaccount.setUserId(entity.getUserId());
		newaccount.setLastLoginTime(new Timestamp(System.currentTimeMillis()));
		
		int row = this.userService.update(newaccount);
		if (row == 1) {
			if (entity != null) {
				entity.setPassword("");
				entity.setMask("");
			}
			map.put("user", entity);
			map.put("code", "0");
			map.put("msg", "登陆成功！");
			return map;
		} else {
			map.put("code", "4");
			map.put("msg", "登陆失败！");
			return map;
		}
	}
	
	/**
	 * 进入首页
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/index")
	public String index(HttpServletRequest request, Model model) {
		return "pages/common/home";
	}
}
